package com.example.myspringboot.config;

import com.example.myspringboot.dto.Book;
import com.example.myspringboot.dto.Person;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Chen Panrui
 * created at 2022/1/20 14:02
 */
@Configuration
public class MyConfig {

    /**
     * You need to be very careful about the order in which bean definitions are added,
     * as these conditions are evaluated based on what has been processed so far. For this reason, we recommend
     * using only @ConditionalOnBean and @ConditionalOnMissingBean annotations on auto-configuration classes
     * (since these are guaranteed to load after any user-defined bean definitions have been added).
     * ConditionalOnMissingBean 在没有Book的时候，才会inject Person，所以要尤其小心顺序的问题
     * 应该在 auto-configuration的class里面添加这个注解
     * @return 实例
     */
    @Bean
    @ConditionalOnMissingBean(Book.class)
    public Person chen(){
        System.out.println("初始化‘陈潘锐’");
        Person person = new Person();
        person.setAge("25");
        person.setName("陈潘锐");
        return person;
    }

    @Bean
    public Book spring(){
        System.out.println("初始化‘spring’");
        Book book = new Book();
        book.setAuthor("someone");
        book.setTitle("springboot");
        return book;
    }
}
